<template>
  <div class="publish-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{
            this.$route.query.id ? "修改文章" : "发布文章"
          }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form
        ref="publish-form"
        :model="article"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="article.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-tiptap
            lang="zh"
            height="350"
            v-model="article.content"
            :extensions="extensions"
            placeholder="请输入文章内容"
          ></el-tiptap>
        </el-form-item>
        <el-form-item label="封面">
          <el-radio-group v-model="article.cover.type">
            <el-radio :label="1">单面</el-radio>
            <el-radio :label="3">三面</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="article.cover.type > 0">
          <upload-image v-for="(cover,index) in article.cover.type "
            :key="cover"
           v-model="article.cover.images[index]"
            />
            <!-- <upload-image v-for="(cover,index) in article.cover.type "
            :key="cover"
            @update-cover="onUpdateCover(index,$event)"
            :cover-image = "article.cover.images[index]"
            /> -->
            
        </template>
        <el-form-item label="频道" prop="channel_id">
          <el-select v-model="article.channel_id" placeholder="请选择活动频道">
            <el-option
              :label="channel.name"
              :value="channel.id"
              v-for="(channel, index) in channels"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onPublish(false)">{{
            this.$route.query.id ? "修改" : "发布"
          }}</el-button>
          <el-button @click="onPublish(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  getArticleChannels,
  addArticle,
  getArticle,
  updateArticle,
} from "@/api/article";
import { uploadImage } from "@/api/image";

import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Image,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  TodoItem,
  TodoList,
  HorizontalRule,
  Fullscreen,
  Preview,
  CodeBlock,
} from "element-tiptap";
import "element-tiptap/lib/index.css";
import UploadImage from "./components/upload-image";
export default {
  name: "PublishIndex",
  components: {
    "el-tiptap": ElementTiptap,
    UploadImage
  },
  props:{},
  data() {
    return {
      channels: [],
      article: {
        title: "", //文章标题
        content: "", //文章内容
        cover: {
          type: 0, //封面类型，-1：自动、0：无图、1：1张、3：3张
          images: [], //封面图片的地址
        },
        channel_id: null,
      },
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 3 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Image({
          // 默认会把图片生成 base64 字符串和内容存储在一起，如果自定义图片上传
          uploadRequest(file) {
            //如果接口要求 Content-Type是 multipart/form-data,则请求他体必须使用 FormData
            const fd = new FormData();
            fd.append("image", file);
            // 第一个 return 是返回一个Promise 对象 为什么？因为 axios本身就是一个返回 Promise对象
            return uploadImage(fd).then((res) => {
              //这个return 是返回最后的结果
              return res.data.data.url;
            });
          }, //图片的上传方法，返回一个 Promise<url>
        }),
        new Underline(), // 下划线
        new Italic(), // 斜体
        new Strike(), // 删除线
        new HorizontalRule(), // 华丽的分割线
        new ListItem(),
        new BulletList(), // 无序列表
        new OrderedList(), // 有序列表
        new TodoItem(),
        new TodoList(),
        new Fullscreen(),
        new Preview(),
        new CodeBlock(),
      ],
      formRules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          {
            min: 5,
            max: 30,
            message: "长度在 5 到 30 个字符",
            trigger: "blur",
          },
        ],
        content: [
          // { required: true, message: '请输入文章内容', trigger: 'change' }
          {
            validator(rule, value, callback) {
              //console.log("content validator");
              if (value === "<p></p>") {
                // 验证失败
                callback(new Error("请输入文章内容"));
              } else {
                // 验证通过
                callback( );
              }
            }
          },
          { required: true, message: "请输入文章内容", trigger: "blur" },
        ],
        channel_id: [{ required: true, message: "请选择文章频道" }],
      },
    }
  },
  computed: {},
  watch: {},
  created() {
    this.loadChannels();

    // 由于我们让发布和修改使用的同一个组件，所以这判断路由参数中有 id，则请求展示文章内容
    if (this.$route.query.id) {
      this.loadArticle();
    }
  },
  mounted() {},
  methods: {
    //加载频道
    loadChannels() {
      getArticleChannels().then((res) => {
        this.channels = res.data.data.channels;
      });
    },
    onPublish(draft = false) {
      this.$refs['publish-form'].validate(valid => {
        if (!valid){
          return
        } 
      // 找到数据接口
      // 封装请求方法
      // 请求提交表单
      // 如果是修改文章，则执行修改操作，否则执行添加操作
      const articleId = this.$route.query.id;
      if (articleId) {
        // 执行修改操作
        updateArticle(articleId, this.article, draft).then((res) => {
          console.log(res);
          this.$message({
            message: `${draft ? "存入草稿" : "发布"}成功`,
            type: "success",
          });
          // 跳转到内容管理页面
          this.$router.push("/article");
        });
      } else {
        addArticle(this.article, draft).then((res) => {
          // 处理响应结果
          // console.log(res)
          this.$message({
            message: `${draft ? "存入草稿" : "发布"}成功`,
            type: "success",
          });
          // 跳转到内容管理页面
          this.$router.push("/article");
        });
      }
      })
    },
    //修改文章内容：加载文章内容
    loadArticle() {
      //console.log('hahhahahah')
      //找到数据接口
      //封装请求方法
      //请求获取数据
      getArticle(this.$route.query.id).then((res) => {
        //console.log(res)
        this.article = res.data.data;
      });
      //模板绑定展示
    },
    onUpdateCover(index,url){
        this.article.cover.images[index] = url
    }
  },
}
</script>

<style scoped lang="less"></style>